package de.jaydev.controller;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import de.jaydev.business.Poll;
import de.jaydev.business.PollAnswer;
import de.jaydev.persistence.PollRepository;

@Controller
public class WebController
{
    private static Logger logger = Logger.getLogger(WebController.class);
    
    @Autowired
    PollRepository pollRepository;
    
    @RequestMapping("home")
    public String loadHomePage()
    {
        logger.debug("loadHomePage");
        return "home";
    }
    
    @RequestMapping("registration")
    public String loadUserRegistration()
    {
        logger.debug("loadUserRegistration");
        return "registration";
    }
    
    @RequestMapping("admin")
    public String loadAdmin()
    {
        logger.debug("loadAdmin");
        return "admin";
    }
    
    @RequestMapping("createPoll")
    public ModelAndView createPoll()
    {
        logger.debug("createPoll");
        
        ModelAndView mav = new ModelAndView("createPoll");
        
        mav.addObject("myPoll", new Poll());
        
        return mav;
    }
    
    @RequestMapping(value = "createPoll", method = RequestMethod.POST)
    public ModelAndView addAnswer(@ModelAttribute("myPoll") Poll poll, @RequestParam String action)
    {
        logger.debug("addAnswer poll=" + poll + "action=" + action);
        
        ModelAndView m = new ModelAndView();
        if (action.equals("Umfrage erstellen"))
        {
            pollRepository.save(poll);
            m.setViewName("home");
        }
        else if (action.equals("+Antwort"))
        {
            poll.getPossibleAnswers().add(new PollAnswer("neue Antwort"));
            m.setViewName("createPoll");
            m.addObject("myPoll", poll);
        }
        
        return m;
    }
  
}
